package com.zerosoft.villagemonitor.controller;

import com.alibaba.fastjson2.JSONObject;
import com.zerosoft.villagemonitor.config.PlatformConfig;
import com.zerosoft.villagemonitor.config.PlatformProperties;
import com.zerosoft.villagemonitor.service.HikPlatformService;
import com.zerosoft.villagemonitor.service.ZLMediaKitService;
import com.zerosoft.villagemonitor.utils.RedisUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@Slf4j
@RequestMapping("/api")
public class MonitorController {
    @Resource
    private PlatformConfig platformConfig;

    @Resource
    private PlatformProperties platformProperties;

    @Resource
    private HikPlatformService hikPlatformService;

    @Resource
    private ZLMediaKitService zlMediaKitService;

    @Resource
    private RedisUtil redisUtil;

    @Value("${spring.application.name}")
    private String appName;

    @RequestMapping("/geturl")
    public String getPlatformProperties() {
        return platformConfig.platformProperties().getUrl();
    }

    @RequestMapping("/getkey")
    public String getPlatformKey() {
        return platformProperties.getKey();
    }

    @RequestMapping("/getrootregion")
    public String getRootRegion() {
        return hikPlatformService.getRootRegion();
    }

    @RequestMapping("/getsubregion/{id}/{page}/{size}")
    public String getSubRegion(@PathVariable("id") String id, @PathVariable("page") String page, @PathVariable("size") String size) {
        return hikPlatformService.getSubRegion(id,page,size);
    }

    @RequestMapping("/getcamera/{id}/{page}/{size}")
    public String getCamera(@PathVariable("id") String id, @PathVariable("page") String page, @PathVariable("size") String size) {
        return hikPlatformService.getCamera(id,page,size);
    }

    @RequestMapping("/getpreviewurls/{id}")
    public String getPreviewUrls(@PathVariable("id") String id) {
        System.out.println("id = " + id);
        //检查是否存在现有ID的拉流代理，如果有，直接返回（可以方便其他调用者直接使用）
        String key = appName + ":" + id;
        String playUrl = zlMediaKitService.getStreamUrl(id);
        if(redisUtil.hasKey(key) && redisUtil.hHasKey(key,"caller") && Integer.parseInt( redisUtil.hget(key,"caller").toString())>0)
        {
            redisUtil.hincr(key,"caller",1);
        }
        else{
            JSONObject jsonObject = JSONObject.parseObject(hikPlatformService.getPreviewUrls(id));
            //添加拉流代理到ZLMediaKit,并将返回的KEY及播放地址返回，key用于播放结束时删除代理
            if(jsonObject.getInteger("code")==0)
            {
                JSONObject data = jsonObject.getJSONObject("data");
                JSONObject response = JSONObject.parseObject( zlMediaKitService.addStreamProxy(data.getString("url"),id));
                System.out.println("response = " + response);
                if(response.getInteger("code")==0)
                {
                    JSONObject resData = response.getJSONObject("data");
                    redisUtil.hset(key,"caller",1);
                    redisUtil.hset(key,"url",playUrl);
                    redisUtil.hset(key,"stream",id);
                    redisUtil.hset(key,"origin_url",data.getString("url"));
                    redisUtil.hset(key, "key",resData.getString("key"));
                }
            }
        }
        Map<String, Object> map = new HashMap<>();
        Map<String, String> data = new HashMap<String, String>();
        map.put("code",0);
        data.put("url",playUrl);
        map.put("data",data);

        return JSONObject.toJSONString(map);

//        return hikPlatformService.getPreviewUrls(id);
    }

    /**
     * 直接根据cameraID获取播放地址
     * @param id    camera的indexCode
     * @return
     */
    @RequestMapping("/getstreamurl/{id}")
    public String getStreamUrl(@PathVariable("id") String id) {
        return hikPlatformService.getPreviewUrls(id);
    }

    @RequestMapping("/getregioninfo/{id}")
    public String getRegionInfo(@PathVariable("id") String id){
        return hikPlatformService.getRegionInfo(id);
    }

    @RequestMapping("/endplay")
    public String endPlay(@PathVariable("stream") String stream) {
        System.out.println("stream = " + stream);
        //不能简单地一直删除代理，需要先检查是否还存在使用者，如果不存在，则删除，否则返回错误信息
        String key = appName + ":" + stream;
        if(redisUtil.hasKey(key) && redisUtil.hHasKey(key,"caller") && Integer.parseInt( redisUtil.hget(key,"caller").toString())>0)
        {
            if(redisUtil.hincr(key,"caller",-1)<=0)
            {
                zlMediaKitService.delStreamProxy(redisUtil.hget(key,"key").toString());
                redisUtil.del(key);
            }
        }
        return "{\"code\": 0}";
    }
}
